using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;
using Microsoft.EntityFrameworkCore;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetUserByIdQueryHandler : IRequestHandler<GetUserByIdQuery, UserDto>
	{
		private readonly IBaseRepository<User> _userRepo;
		private readonly IBaseRepository<UserRole> _userRoleRepo;
		private readonly IBaseRepository<Role> _roleRepo;
		private readonly IBaseRepository<RolePermission> _rolePermissionRepo;
		private readonly IBaseRepository<Permission> _permissionRepo;

		public GetUserByIdQueryHandler(
			IBaseRepository<User> userRepo,
			IBaseRepository<UserRole> userRoleRepo,
			IBaseRepository<Role> roleRepo,
			IBaseRepository<RolePermission> rolePermissionRepo,
			IBaseRepository<Permission> permissionRepo)
		{
			_userRepo = userRepo;
			_userRoleRepo = userRoleRepo;
			_roleRepo = roleRepo;
			_rolePermissionRepo = rolePermissionRepo;
			_permissionRepo = permissionRepo;
		}

		public async Task<UserDto> Handle(GetUserByIdQuery request, CancellationToken cancellationToken)
		{
			var user = await _userRepo.GetModel(x => 
				x.UserId == request.UserId && !x.IsDeleted);
			
			if (user == null)
			{
				throw new Exception("用户不存在");
			}

			// 获取用户角色
			var userRoleIds = _userRoleRepo.GetAll()
				.Where(x => ((UserRole)x).UserId == user.UserId)
				.Select(x => ((UserRole)x).RoleId)
				.ToList();

			var roles = new List<RoleDto>();
			var permissions = new List<PermissionDto>();

			if (userRoleIds.Any())
			{
				// 获取角色信息
				roles = await _roleRepo.GetAll()
					.Where(x => userRoleIds.Contains(x.RoleId))
					.Select(r => new RoleDto
					{
						RoleId = r.RoleId,
						Name = r.Name,
						Description = r.Description,
						IsActive = r.IsActive,
						CreatedAt = r.CreatedAt,
						UpdatedAt = r.UpdatedAt
					})
					.ToListAsync(cancellationToken);

				// 获取权限ID
				var permissionIds = _rolePermissionRepo.GetAll()
					.Where(x => userRoleIds.Contains(((RolePermission)x).RoleId))
					.Select(x => ((RolePermission)x).PermissionId)
					.Distinct()
					.ToList();

				// 获取权限信息
				if (permissionIds.Any())
				{
					permissions = await _permissionRepo.GetAll()
						.Where(x => permissionIds.Contains(x.PermissionId))
						.Select(p => new PermissionDto
						{
							PermissionId = p.PermissionId,
							Name = p.Name,
							Code = p.Code,
							Group = p.Group,
							Description = p.Description,
							IsMenu = p.IsMenu,
							IsActive = p.IsActive,
							CreatedAt = p.CreatedAt,
							UpdatedAt = p.UpdatedAt
						})
						.Distinct()
						.ToListAsync(cancellationToken);
				}
			}

			return new UserDto
			{
				UserId = user.UserId,
				UserName = user.UserName,
				Email = user.Email,
				FullName = user.FullName,
				Phone = user.Phone,
				EmployeeId = user.EmployeeId,
				IsActive = user.IsActive,
				LastLoginAt = user.LastLoginAt,
				LastLoginIp = user.LastLoginIp,
				CreatedAt = user.CreatedAt,
				UpdatedAt = user.UpdatedAt,
				Roles = roles,
				Permissions = permissions
			};
		}
	}
}

